<template>
  <div class="import-container">
    <el-dialog
      title="导入设备"
      :visible.sync="dialogVisible"
      width="630px"
      :before-close="closeAddDialog"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <div class="mini-dialog">
        <h3 class="title" style="margin-top: 5px">导入文件编辑注意事项：</h3>
        <div class="import-item">1、 已存在设备无法导入</div>
        <div class="import-item">
          2、请在对应单元格填写设备编码、{{ labelName }}
        </div>
        <div class="import-item">
          3、Excel输入单元格内不能出现中文、特殊符号及空格
        </div>
      </div>

      <el-form
        :inline="true"
        :model="formInline"
        class="demo-form-inline"
        :rules="rules"
        ref="ruleForm"
      >
        <el-form-item style="width: 170px; margin-right: 10px" prop="productId">
          <el-select
            v-model="formInline.productId"
            placeholder="请选择产品类型"
            @change="onChange"
          >
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="classMark">
          <el-select
            style="width: 170px"
            v-loadMore="loadMore2"
            v-model="formInline.classMark"
            placeholder="请选择产品型号"
            @change="onChange2"
          >
            <el-option
              v-for="item in classMarkList"
              :label="item.model"
              :value="item.model"
              :key="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading2"
              :style="loading2 ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>

        <el-form-item style="width: 175px" prop="protocol">
          <el-select v-model="formInline.protocol" placeholder="请选择通信协议">
            <el-option
              v-for="item in protocolList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item style="width: 160px" prop="manufacturerId">
          <el-select v-model="formInline.manufacturerId" filterable placeholder="请选择厂商">
            <el-option v-for="item in manufacturerList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
      </el-form>

      <div class="content">
        <div>
          <div class="btn-row">
            <el-upload
              ref="upload"
              action="#"
              :limit="1"
              accept=".xls,.xlsx"
              :multiple="false"
              :before-upload="beforeUpload"
              :on-change="handChange"
              :on-exceed="handleExceed"
              :auto-upload="false"
              :http-request="uploadRequest"
            >
              <el-button slot="trigger" size="small" type="primary">
                选取文件
              </el-button>
              <el-button size="small" type="info" @click="handleDownload">
                下载模板
              </el-button>
              <div class="el-upload__tip" slot="tip">
                只能上传Excel文件，且不超过500kb
              </div>
              <!-- <div class="el-upload__tip import-result" slot="tip">
                <el-collapse accordion style="width: 360px">
                  <el-collapse-item name="1">
                    <template slot="title">
                      <div style="color: #409eff">
                        <span>设备总数：{{ result.total }}</span>
                      </div>
                      <div style="color: #58b850; margin-left: 20px">
                        <span>成功：{{ result.success }}</span>
                      </div>
                      <div style="color: #ff0000; margin-left: 20px">
                        <span>失败：{{ result.failed }}</span>
                      </div>
                    </template>
<div>{{ result.failedList }}</div>
</el-collapse-item>
</el-collapse>
</div> -->
            </el-upload>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          slot="trigger"
          size="small"
          type="primary"
          @click="importStart"
        >
          开始导入
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqDeviceImport,
  reqProductList,
  reqManufacturerList,
  reqProductModelPage,
  reqCameraImport,
} from "@api/api";
import { log } from "ezuikit-js";
import loadMore from "@mixin/loadMore";

export default {
  name: "importDevice",
  mixins: [loadMore],
  data() {
    return {
      dialogVisible: false,
      result: {
        total: 0,
        success: 0,
        failed: 0,
        failedList: "",
      },
      isXlsx: true,
      /* mini弹框 */
      formInline: {
        productId: "",
        classMark: "",
        protocol: "",
      },
      productList: [],
      manufacturerList: [],
      rules: {
        productId: [
          { required: true, message: "请选择产品类型", trigger: "change" },
        ],
        classMark: [
          { required: true, message: "请选择产品型号", trigger: "change" },
        ],
        protocol: [
          { required: true, message: "请选择通信协议", trigger: "change" },
        ],
      },
      classMarkList: [],
      sysInstanceIndex2: 1,
      sysInstanceTotalPages2: 10,
      loading2: false,
      protocolList: [
        {
          id: 1,
          name: "电信物模型标准规范",
        },
        {
          id: 2,
          name: "移动铠湾规范",
        },
        {
          id: 3,
          name: "移动安消规范",
        },
        {
          id: 6,
          name: "声光规范",
        },
        {
          id: 7,
          name: "珠海慧芯",
        },
      ],
      selectedItem: {},
      labelName: "设备id",
    };
  },
  methods: {
    // 获取产品型号
    async ProductModelPage() {
      let res = await reqProductModelPage(this.sysInstanceIndex2, 10, {
        productId: this.formInline.productId,
      });
      // console.log(res);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages2 = res.data.total;
      this.classMarkList = [...this.classMarkList, ...res.data.rows];
    },
    async loadMore2() {
      if (this.sysInstanceIndex2 >= Math.ceil(this.sysInstanceTotalPages2 / 10))
        return;
      this.sysInstanceIndex2++;
      this.loading2 = true;
      // 获取列表数据的方法
      await this.ProductModelPage();
      this.loading2 = false;
    },

    onChange(val) {
      this.selectedItem = this.productList.find((item) => item.id === val);
      if (this.selectedItem.deviceType == "Camera") {
        this.labelName = "序列号";
        this.protocolList = [
          {
            id: 4,
            name: "萤石协议",
          },
          {
            id: 5,
            name: "国标协议",
          },
        ];
      } else {
        this.labelName = "设备id";
        this.protocolList = [
          {
            id: 1,
            name: "电信物模型标准规范",
          },
          {
            id: 2,
            name: "移动铠湾规范",
          },
          {
            id: 3,
            name: "移动安消规范",
          },
          {
            id: 6,
            name: "声光规范",
          },
          {
            id: 7,
            name: "珠海慧芯",
          },
        ];
      }
      this.classMarkList = [];
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.formInline.classMark = "";
      this.ProductModelPage();
    },

    onChange2(val) {
      this.formInline.protocol = "";
      if (this.selectedItem.deviceType == "Camera") {
        if (val == "V380") {
          this.protocolList = [
            {
              id: 5,
              name: "国标协议",
            },
          ];
        } else {
          this.protocolList = [
            {
              id: 4,
              name: "萤石协议",
            },
            {
              id: 5,
              name: "国标协议",
            },
          ];
        }
      } else {
        this.protocolList = [
          {
            id: 1,
            name: "电信物模型标准规范",
          },
          {
            id: 2,
            name: "移动铠湾规范",
          },
          {
            id: 3,
            name: "移动安消规范",
          },
          {
            id: 6,
            name: "声光规范",
          },
          {
            id: 7,
            name: "珠海慧芯",
          },
        ];
      }
    },

    //   获取产品列表
    async getProductList() {
      const res = await reqProductList();
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // console.log(res);
      this.productList = res.data.rows;
    },
    // 获取厂商列表
    async getManufacturerList() {
      const res = await reqManufacturerList();
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.manufacturerList = res.data.rows;
    },
    // 上传前验证
    beforeUpload(file) {
      let Xls = file.name.split(".");
      if (Xls[1] !== "xls" || Xls[1] !== "xlsx") {
        this.isXlsx = false;
      }
    },
    // 因为 before-upload 是指在文件上传之前、文件已被选中，但还没上传的时候触发，而设置了 :auto-upload=“false” 后，文件上传事件不被再次调用，所以 before-upload 不生效，所以，限制大小的时候，需绑定在 :on-change 里面
    handChange(file) {
      const limitSize = file.size / 1024 / 1024;
      if (limitSize > 0.5) {
        this.$refs.upload.clearFiles();
        this.$modal.notifyWarning("上传文件大小不能超过 500KB!");
        return false;
      }
      let Xls = file.name.split(".");
      if (Xls[1] !== "xls" && Xls[1] !== "xlsx") {
        this.$refs.upload.clearFiles();
        this.$modal.notifyWarning("只能上传Excel文件!");
      }
    },
    handleExceed() {
      this.$modal.notifyWarning(`当前限制选择 1 个文件`);
    },
    // 自定义上传
    async uploadRequest(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      // formData.append("belongToPlatform", this.formInline.belongToPlatform);
      const loading = this.$loading({
        lock: true,
        text: "正在导入，请耐心等待~",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.7)",
      });
      console.log(this.formInline);
      let res = "";
      if (this.selectedItem.deviceType == "Camera") {
        res = await reqCameraImport(formData, this.formInline);
      } else {
        res = await reqDeviceImport(formData, this.formInline);
      }
      loading.close();
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.closeAddDialog();
      setTimeout(() => {
        this.$parent.getDataList();
      }, 1500);
      // if (res.data.result.failed === 0) {
      //   // this.$modal.notifySuccess('导入成功');
      // } else if (res.data.result.failed > 0 && res.data.result.success > 0) {
      //   // this.$modal.notifyWarning('导入有失败');
      // } else {
      //   // this.$modal.notifyWarning('全部导入失败');
      // }
      // this.result.total = res.data.result.total;
      // this.result.success = res.data.result.success;
      // this.result.failed = res.data.result.failed;
      // if (res.data.result.failedList[0]) {
      //   this.result.failedList = res.data.result.failedList.toString();
      // }
    },
    handleDownload() {
      if (this.formInline.productId == "")
        return this.$modal.notifyWarning("请选择产品类型");
      // location.href =
      //   "https://huhutong2020.oss-cn-shenzhen.aliyuncs.com/2021/12/24/e1908bf30da2498c84b01be61cbe00ff.xls";
      var self = this;
      import("../../../../vendor/Export2Excel").then((excel) => {
        if (this.selectedItem.deviceType == "Camera") {
          const tHeader = ["设备编码（必填）", "序列号（必填）"];
          const filterVal = ["imei", "sn"];
          const list = [
            {
              imei: "187634455783456",
              sn: "1104068",
            },
            {
              imei: "187634455783457",
              sn: "1104069",
            },
            {
              imei: "187634455783458",
              sn: "1104070",
            },
          ];
          const data = self.formatJson(filterVal, list);

          excel.export_json_to_excel({
            header: tHeader, //表头
            data, //json数据
            filename: "摄像机导入模板", //导出文件名
            // autoWidth: true, //宽度是否自适应
            bookType: "xlsx", //导出文件后缀名
          });
        } else {
          const tHeader = [
            "设备编码（必填）",
            "设备ID（AEP程序必填）",
            "设备MAC",
          ];
          const filterVal = ["imei", "deviceId", "deviceMac"];
          const list = [
            {
              imei: "187634455783456",
              deviceId: "1456789876",
              deviceMac: "0011040682a7",
            },
            {
              imei: "187634455783457",
              deviceId: "1456789877",
              deviceMac: "0011040682a8",
            },
            {
              imei: "187634455783458",
              deviceId: "1456789878",
              deviceMac: "0011040682a9",
            },
          ];
          const data = self.formatJson(filterVal, list);

          excel.export_json_to_excel({
            header: tHeader, //表头
            data, //json数据
            filename: "导入模板", //导出文件名
            // autoWidth: true, //宽度是否自适应
            bookType: "xlsx", //导出文件后缀名
          });
        }
      });
      this.miniDialogVisible = false;
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
    // 正式上传
    importStart() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.$refs.upload.submit();
        }
      });
    },
    // 点击关闭大弹框
    closeAddDialog() {
      this.dialogVisible = false;
      this.classMarkList = [];
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      // this.result.total = this.result.success = this.result.failed = 0;
      // this.result.failedList = "";
      this.$refs.ruleForm.resetFields();
      this.$refs.upload.clearFiles();
      // this.$parent.getDeviceList();
    },
  },
};
</script>

<style lang="less" scoped>
@import url("../../../common.less");

.mini-dialog {
  margin: 10px 0 20px 24px;
  color: @primaryThemeTxtColor;
}

.el-upload__tip {
  color: @primaryThemeTxtColor;
}

.content {
  padding-left: 21px;
  width: 350px;
  position: relative;
  top: 0;
  bottom: 0;
  left: 20px;
  right: 0;

  // 按钮行
  .btn-row {
    .el-button {
      margin-right: 20px;
    }
  }
}

/* mini弹框 */
.title {
  line-height: 30px;
}

.import-item {
  line-height: 24px;
}

::v-deep .el-collapse {
  border: none;
}

::v-deep .el-icon-arrow-right {
  color: @primaryThemeTxtColor;
}

::v-deep .el-input__inner {
  height: 32px !important;
}

form {
  padding-left: 40px !important;
}
</style>
